package com.sniper.springmvc.freemarker;

import freemarker.ext.beans.BeansWrapper;
import freemarker.template.*;
import org.springframework.ui.ModelMap;

import javax.servlet.ServletContext;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Locale;
import java.util.Map;

public class FreeMarkerUtil {

    private static Version version = new Version("2.3.25");
    private static Charset charset = Charset.forName("utf-8");
    private static Configuration config = new Configuration(version);
    private static Class<?>[] defaultStaticClasses = {};

    protected void setDefaultStaticModel(ModelMap map) {
        for (Class<?> clz : defaultStaticClasses) {
            String name = clz.getSimpleName();
            map.addAttribute(name, getStaticModel(clz));
        }
    }

    private static Object getStaticModel(Class<?> clz) {
        BeansWrapper beansWrapper = new BeansWrapper(version);
        try {
            return beansWrapper.getStaticModels().get(clz.getName());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 静态方法调用
     *
     * @param clz
     * @return
     */
    public static TemplateHashModel getFreeMarkerStaticModel(Class<?> clz) {
        TemplateHashModel dataUtil = null;
        BeansWrapper beansWrapper = new BeansWrapper(version);
        TemplateHashModel model = beansWrapper.getStaticModels();
        try {
            dataUtil = (TemplateHashModel) model.get(clz.getName());
        } catch (TemplateModelException e) {
            e.printStackTrace();
        }

        return dataUtil;
    }

    /**
     * @param templateName 模板名字
     * @param root         模板根 用于在模板内输出结果集
     * @param out          输出对象 具体输出到哪里
     */
    public static void processTemplate(Configuration config, String templateName, Map<?, ?> root, Writer out) {
        try {
            //获得模板
            Template template = config.getTemplate(templateName, charset.name());
            //生成文件（这里是我们是生成html）
            template.process(root, out);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
                out = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void write(String dirPath) throws FileNotFoundException, UnsupportedEncodingException {
        //html生成之后存放的路径
        File path = new File(dirPath);
        //生成的文件的名字
        String indexFileName = "index.html";
        /**
         * 判断是否已经存在该html文件，存在了就直接访问html ，不存在生成html文件
         */
        Writer out = new OutputStreamWriter(new FileOutputStream(path), charset.name());
        //生成html文件

    }

    /**
     * 初始化模板配置
     *
     * @param servletContext javax.servlet.ServletContext
     * @param templateDir    模板位置
     */
    public static void initConfig(ServletContext servletContext, String templateDir) {
        config.setLocale(Locale.CHINA);
        config.setDefaultEncoding(charset.name());
        config.setEncoding(Locale.CHINA, charset.name());
        config.setServletContextForTemplateLoading(servletContext, templateDir);
        config.setObjectWrapper(new DefaultObjectWrapper(version));
    }


}
